<template>
  <el-row class="app-container">
    <!-- 财物登记 -->
    <el-row class="top">
      <span>登记单</span>
      <div>
        <el-form size="mini" :model="wenshuIdObj" label-width="110px" label-position="left">
          <el-form-item label="关联案件文书号">
            <el-input v-model="wenshuIdObj.wenshuId" placeholder="请输入关联案件文书号" clearable :style="{ width: '100%' }">
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="wenshuIdObj.wenshuId" placeholder="请输入关联案件文书号" clearable style="display: none;">
            </el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-row>

    <el-form ref="elForm" :model="formData" :rules="rules" :disabled="disabledFormData" size="medium" label-width="100px" label-position="left">
      <el-row class="row">
        <el-row>
          <el-col :span="12">
            <p>当事人</p>
          </el-col>
          <el-col :span="12">
            <p>案件信息</p>
          </el-col>
        </el-row>
        <hr>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-row :gutter="15">
              <el-form-item label="" prop="type">
                <el-radio-group v-model="formData.type" size="medium">
                  <el-radio v-for="(item, index) in typeOptions" :key="index" :label="item.value" :disabled="item.disabled">{{item.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-row style="paddingLeft:10px;">
                <el-col :span="9">
                  <el-form-item label="姓名" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入姓名" clearable :style="{width: '100%'}">
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="9">
                  <el-form-item label="性别" prop="sex" v-if="formData.type==='1'">
                    <el-select v-model="formData.sex" placeholder="请输入性别" clearable :style="{width: '100%'}">
                      <el-option v-for="(item, index) in dict.type.fianncial_registry_sex" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="法人" prop="legalPerson" v-else>
                    <el-input v-model="formData.legalPerson" placeholder="请输入法人" clearable :style="{width: '100%'}">
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-col :span="14">
                <el-form-item label="联系电话" prop="phone">
                  <el-input v-model="formData.phone" placeholder="请输入联系电话" clearable :style="{width: '100%'}">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item label="身份证号码" prop="idCardNo" v-if="formData.type==='1'">
                  <el-input v-model="formData.idCardNo" placeholder="请输入身份证号码" clearable :style="{width: '100%'}">
                  </el-input>
                </el-form-item>
                <el-form-item label="现场负责人" prop="scenePrincipal" v-else>
                  <el-input v-model="formData.scenePrincipal" placeholder="请输入现场负责人" clearable :style="{width: '100%'}">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="14" v-if="formData.type==='2'">
                <el-form-item label="统一信用证" prop="idCardNo">
                  <el-input v-model="formData.idCardNo" placeholder="请输入统一信用证" clearable :style="{width: '100%'}">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item label="住址" prop="address">
                  <el-input v-model="formData.address" placeholder="请输入住址" clearable :style="{width: '100%'}">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="12">
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item label="强制措施" prop="isCoercive">
                  <el-radio-group v-model="formData.isCoercive" size="medium">
                    <el-radio v-for="(item, index) in isQiangzhiOptions" :key="index" :label="item.value" :disabled="item.disabled">{{item.label}}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item label="执法案由" prop="cause">
                  <el-input v-model="formData.cause" placeholder="请输入执法案由" clearable :style="{width: '100%'}">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item label="执法地点" prop="lawAddress">
                  <el-input v-model="formData.lawAddress" placeholder="请输入执法地点" clearable :style="{width: '100%'}"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item label="文书编号" prop="caseNum">
                  <el-input v-model="formData.caseNum" placeholder="请输入文书编号" clearable :style="{width: '100%'}"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <hr>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-row :gutter="15">
              <el-col :span="14">
                <el-form-item label="办案单位" prop="uhId">
                  <el-select style="width:100%;" @change="uhIdChange" v-model="formData.uhId" filterable placeholder="请选择办案单位">
                    <el-option v-for="item in uhIdList" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item label="办案人员" prop="phName">
                  <el-select style="width:100%;" v-model="formData.phName" multiple filterable allow-create default-first-option placeholder="请选择办案人员">
                    <el-option v-for="item in personList.filter(e=>e.value === formData.uhId)" :key="item.label" :label="item.label" :value="item.label">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item label="保管中心" prop="wId">
                  <el-select v-model="formData.wId" placeholder="请选择类型" clearable :style="{width: '100%'}">
                    <el-option v-for="(item, index) in depotList" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="12">
            <el-row :gutter="15">
              <el-form-item label="现场图片" prop="imgUrl" required>
                <image-upload v-model="formData.imgUrl" />
              </el-form-item>
            </el-row>
          </el-col>
        </el-row>
      </el-row>
      <hr>
      <el-row class="add">
        <span>
          登记明细
        </span>
        <el-button class="sacw button" size="large" @click="addPropertyInfos" style="marginBottom:10px;">
          新增
        </el-button>
      </el-row>
      <el-table :row-class-name="tableRowClassName" v-loading="loading" :data="formData.financialInfos">
        <el-table type="selection" width="55" align="center" />
        <el-table-column label="物品编号" align="center" prop="serialNum">
          <template slot-scope="scope">
            <el-input v-model="scope.row.serialNum" placeholder="请输入物品编号" clearable :style="{width: '100%'}">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="物品名称" align="center" prop="name">
          <template slot-scope="scope">
            <el-input v-model="scope.row.name" placeholder="请输入物品名称" clearable :style="{width: '100%'}">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="物品类型" align="center" prop="type">
          <template slot-scope="scope">
            <el-select v-model="scope.row.type" placeholder="请选择类型" clearable :style="{width: '100%'}">
              <el-option v-for="(item, index) in dict.type.financial_property_type" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="规格" align="center" prop="description">
          <template slot-scope="scope">
            <el-input v-model="scope.row.description" placeholder="请选择规格" clearable :style="{width: '100%'}">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="count">
          <template slot-scope="scope">
            <el-input v-model="scope.row.count" type='number' min="1" placeholder="请输入数量" clearable :style="{width: '100%'}">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="财物图片" align="center" class="imgMini" prop="imgUrl" width="100">
          <template slot-scope="scope">
            <image-upload v-model="scope.row.imgUrl" :limit="1" />
          </template>
        </el-table-column>
        <el-table-column label="文书编号" align="center" prop="qrId">
          <template slot-scope="scope">
            <el-input v-model="scope.row.caseNum" placeholder="请输入文书编号" clearable :style="{width: '100%'}"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="二维码编号" align="center" prop="qrId">
          <template slot-scope="scope">
            <el-select filterable v-model="scope.row.qrId" placeholder="请选择二维码编号" clearable :style="{width: '100%'}">
              <el-option v-for="(item, index) in prcodeOptions" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="propertyInfosDelete(scope.row.index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div class="bottom">
      <p>
        <span>状态</span>
      </p>
      <div class="buttons">
        <el-button class="sacw" size="large" @click="disabledFormData=false">
          编辑
        </el-button>
        <el-button class="sacw" size="large" @click="submitForm">
          {{formData.id ? '保存':'添加'}}
        </el-button>
        <el-button class="sacw" size="large" @click="cancel">
          取消
        </el-button>
      </div>
    </div>
  </el-row>
</template>

<script>
import { addRegisterInfo, getCaseNum, getRegistryList } from '@/api/property/registerInfo.js'
import { getPropertyInfo } from '@/api/property/propertyList.js'
import { qrCodeDispose, warehouseDispose, unitDispose, personnelDispose } from '@/api/property/dispose.js'
import { parseTime } from '@/utils/ruoyi'

export default {
  name: 'registerInfo',
  dicts: ['financial_property_type', 'fianncial_registry_sex'],
  data () {
    return {
      // 是否禁用登记单
      disabledFormData: false,
      // 上传图片路径
      actionImg: 'http://106.12.222.224:8080/common/upload',
      // 文书编号
      wenshuIdObj: {
        wenshuId: '',
      },
      // 遮罩层
      loading: false,
      // 财物登记表格数据
      // disposalList: [{
      //   orderId: '123'
      // }],
      // 办案人员列表
      personList: [],
      // 办案单位列表
      uhIdList: [],
      // 保管中心列表
      depotList: [],
      formData: {
        "infoMsg": null, // 案件信息
        "caseNum": null, // 文书ID,案件编号
        "type": '1', // 登记类型:1 个人,2 单位(默认:个人)
        "name": null, // 当事人姓名,单位名称
        "sex": null, // 当事人性别:1 男,0 女(默认:男)
        "phone": null, // 当事人/单位 联系电话
        "idCardNo": null, // 身份证号码/统一信用证号码
        "address": null, // 当事人住址/单位地址
        "legalPerson": null, // 单位法定代表人
        "scenePrincipal": null, // 现场负责人
        "isCoercive": null, // 强制措施:1 扣押,2 先行压扣登记(默认:扣押)
        "cause": null, // 执法案由
        "lawAddress": null, // 执法地点
        "imgUrl": null, // 现场照片
        "uhId": null, // 登记案件所属办案单位ID
        "phName": [], // 登记案件办案人员
        "wId": null, // 所属仓库/保管中心ID
        "financialInfos": [
          {
            caseNum: null, // 文书编号
            "serialNum": null, // 物品编号
            "name": null, // 物品名称
            "type": null, // 物品类型:1 普通物品,2 特殊物品,3 车辆
            "description": null, // 物品规格
            "count": null, // 物品数量
            "imgUrl": null, // 物品图片
            "qrId": null, // 绑定的二维码ID
            "registryStatus": '1', // 登记状态:1 已登记,2 已入库,3 已出库
            "treatmentStatus": '0' //处置状态:1 退还,2 移交,3 销毁,0 无操作
          }
        ]
      },
      rules: {
        legalPerson: [{
          required: true,
          message: '请输入法人',

        }],
        scenePrincipal: [{
          required: true,
          message: '请输入现场负责人',

        }],
        type: [{
          required: true,
          message: '不能为空',
          // trigger: 'change'

        }],
        name: [{
          required: true,
          message: '请输入姓名',

        }],
        sex: [{
          required: true,
          message: '请输入性别',
          trigger: 'change'
        }],
        phone: [{
          required: true,
          message: '请输入手机号',

        }, {
          pattern: /^1\d{10}$/,
          message: '手机号格式错误',

        }],
        idCardNo: [{
          required: true,
          message: '请输入身份证号码',

        }, {
          pattern: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
          required: true,
          message: '身份证号码格式错误',

        }],
        address: [{
          required: true,
          message: '请输入住址',

        }],
        isCoercive: [{
          required: true,
          message: '强制措施不能为空',

        }],
        cause: [{
          required: true,
          message: '请输入执法案由',

        }],
        lawAddress: [{
          required: true,
          message: '请输入执法地点',

        }],
        caseNum: [{
          required: true,
          message: '请输入文书编号',

        }],
        uhId: [{
          required: true,
          message: '请输入办案单位',

        }],
        phName: [{
          required: true,
          message: '请输入办案人员',

        }],
        wId: [{
          required: true,
          message: '请输入保管中心',

        }],
        imgUrl: [{
          required: true,
          message: '请选择图片',

        }]
      },
      // 二维码编号选择框
      prcodeOptions: [],
      propertyTypeOptions: [{
        "label": "普通物品",
        "value": '1'
      }, {
        "label": "特殊物品",
        "value": '2'
      }, {
        "label": "车辆",
        "value": '3'
      }],
      typeOptions: [{
        "label": "个人",
        "value": '1'
      }, {
        "label": "单位",
        "value": '2'
      }],
      sexOptions: [{
        "label": "男",
        "value": '0'
      }, {
        "label": "女",
        "value": '1'
      }],
      isQiangzhiOptions: [{
        "label": "扣押",
        "value": '1'
      }, {
        "label": "先行扣押登记",
        "value": '2'
      }],
      throttle: null,
    }
  },
  watch: {
    // 监听关联案件文书号
    wenshuIdObj: {
      deep: true,
      handler: function ({ wenshuId: id }, oldV) {
        if (!id) return this.emptyFormData()
        clearTimeout(this.throttle)
        this.throttle = setTimeout(() => {
          getCaseNum(id).then(res => {
            if (res.data) {
              this.disabledFormData = true
              this.formData = res.data
              this.formData.phName = this.formData.phName.split(',')
              // this.formData.id = null
            }
          })
        }, 500);
      }
    }
  },
  mounted () {
    parseTime,
      // 请求处理二维码编号
      qrCodeDispose().then(e => {
        this.prcodeOptions = e
      })

    // 处理仓库列表数据
    warehouseDispose().then(e => {
      this.depotList = e
    })

    // 处理办案单位数据
    unitDispose().then(e => {
      this.uhIdList = e
    })

    // 处理办案人员数据
    personnelDispose().then(e => {
      this.personList = e
    })

    getPropertyInfo().then(res => {
      const count = res.rows.map(e => e.count).reduce((e, s) => e + s)
      let dateCount = {
        twoM: [],
        twoD: [],
        threeM: [],
        threeD: [],
      }

      res.rows.forEach(e => {
        const twoM = parseTime(e.registryTime, '{m}') === parseTime(new Date(), '{m}')
        const twoD = parseTime(e.registryTime, '{d}') === parseTime(new Date(), '{d}')

        for (const key in dateCount) {
          const type = key === 'threeM' || key === 'threeD' ? '3' : '2'
          const date = key === 'threeM' || key === 'twoM' ? twoM : twoD
          if (e.registryStatus === type && date) {
            dateCount[key].push(e.count)
          }
        }
      })

      for (const key in dateCount) {
        dateCount[key] = dateCount[key].length ? dateCount[key].reduce((e, s) => e + s) : 0
      }
    })

  },
  methods: {
    // 修改办案单位清空办案人员
    uhIdChange () {
      this.formData.phName = []
    },

    // 取消
    cancel () {
      this.emptyFormData()
    },

    // 登记单初始化
    emptyFormData () {
      this.formData.financialInfos = this.formData.financialInfos.length ? [this.formData.financialInfos[0]] : []
      this.disabledFormData = false
      this.wenshuIdObj.wenshuId = ''
      for (const key in this.formData) {
        if (key === 'financialInfos') {
          if (!this.formData.financialInfos.length) return
          this.formData.financialInfos.forEach((e, index) => {
            for (const keys in this.formData.financialInfos[index]) {
              this.formData.financialInfos[index][keys] = null
            }
          })
        } else if (key === 'type') {
          this.formData.type = '1'
        } else {
          this.formData[key] = null
        }
      }
    },

    // 添加登记明细
    addPropertyInfos () {
      if (this.disabledFormData) return this.$modal.msgWarning("目前为不可编辑状态");
      this.formData.financialInfos.push({
        caseNum: null, // 文书编号
        "serialNum": null, // 物品编号
        "name": null, // 物品名称
        "type": null, // 物品类型:1 普通物品,2 特殊物品,3 车辆
        "description": null, // 物品规格
        "count": null, // 物品数量
        "imgUrl": null, // 物品图片
        "qrId": null, // 绑定的二维码ID
        "registryStatus": '1', // 登记状态:1 已登记,2 已入库,3 已出库
        "treatmentStatus": '0' //处置状态:1 退还,2 移交,3 销毁,0 无操作
      })
    },

    // 删除登记明细列表
    propertyInfosDelete (index) {
      this.$confirm('确认要删除吗?')
        .then(_ => {
          this.formData.financialInfos.splice(index, 1)
        })
        .catch(_ => { });
    },

    // 把表格每一行的索引放进 row
    tableRowClassName ({ row, rowIndex }) {
      row.index = rowIndex
    },

    // 处理文书编号和物品编号是否是唯一存在
    async sole () {
      let s = true

      let serialNums = [], caseNums = [], financialCaseNums = []

      await getRegistryList().then(res => {
        res.rows.map(item => {
          item.financialInfos.map(e => {
            serialNums.push({ item: String(e.serialNums), id: item.id })
            financialCaseNums.push({ item: e.caseNum, id: item.id })
          })
          caseNums.push({ item: item.caseNum, id: item.id })
        })

        caseNums.map((res, index) => {
          if (res.item === this.formData.caseNum && res.id !== this.formData.id) {
            this.formData.caseNum = null
            this.$modal.msgWarning("文书编号已存在请修改后再添加");
            s = false
          }
        })

        this.formData.financialInfos.forEach((e, index) => {
          console.log(serialNums);
          serialNums.map((res) => {
            if (res.item === e.serialNums && res.id !== this.formData.id) {
              this.formData.financialInfos[index].serialNums = null
              this.$modal.msgWarning("物品编号已存在请修改后再添加");
              s = false
            }
          })

          financialCaseNums.map((res) => {
            if (res.item === e.caseNum && res.id !== this.formData.id) {
              this.formData.financialInfos[index].caseNum = null
              this.$modal.msgWarning("物品文书编号已存在请修改后再添加");
              s = false
            }
          })

          let serialNum = [], qrId = [], caseNum = []
          let add = [{ label: 'serialNum', value: '编号' }, { label: 'qrId', value: '二维码编号' }, { label: 'caseNum', value: '文书编号' }]

          // 验证财物列表某些字段是否重复
          add.map(item => {
            if ([item.label].includes(e[item.label])) {
              this.formData.financialInfos[index][item.label] = null
              this.$modal.msgWarning(`物品${item.value}已重复请修改后再添加`);
              s = false
            }
            [item.label].push(e[item.label])
          })
        })
      })

      return s
    },

    // 验证表格数据是否填满
    async verification () {
      let s = true
      const add = ['searchValue', 'createBy', 'updateBy', 'remark', 'storeImg', 'deliverImg', 'updateTime', 'caseNum', 'financialRegistries']
      await this.formData.financialInfos.forEach((res, index) => {
        for (const key in res) {
          if (!this.formData.financialInfos[index][key] && key !== 'index' && !add.includes(key)) {
            this.$message({
              message: '请完善物品信息',
              type: 'warning'
            });
            console.log(key);
            s = false
          }
        }
      })
      return s
    },

    // 提交表单
    async submitForm () {
      if (this.disabledFormData) return this.$modal.msgWarning("目前为不可编辑状态");

      this.$confirm(`确认${this.formData.id ? '保存' : '添加'}吗?`)
        .then(() => {
          // 验证表单数据是否填满
          this.$refs['elForm'].validate(valid => {
            if (!valid) return
            if (!this.formData.financialInfos.length) return this.$modal.msgWarning("请添加财物")

            // 判断是否文书编号物品编号是否为空
            this.verification().then(e => {
              e && this.sole().then(res => {
                if(!res) return
                // loading加载
                const loading = this.$loading({
                  lock: true,
                  text: 'Loading',
                  spinner: 'el-icon-loading',
                  background: 'rgba(0, 0, 0, 0.7)'
                });

                // 保存登记表
                 addRegisterInfo({ ...this.formData, phName: this.formData.phName.join(',') }).then(e => {
                  // 去除 loading 加载
                  loading.close();
                  e.code === 200 && this.$message({
                    message: '保存成功',
                    type: 'success'
                  });
                  this.$router.back()
                }).catch(() => {
                  loading.close();
                  this.$modal.alertError("提交错误请稍后重试");
                })
              })
            })

          })


        })
        .catch(() => { });

    },
  },
}
</script>

<style scoped lang="scss">
::v-deep .el-upload-list__item {
  width: 80px;
  height: 80px;
}
::v-deep .el-upload--picture-card {
  width: 80px;
  height: 80px;
  line-height: 90px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
  border: 1px solid #eee;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px solid #eee;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border: 1px solid #eee;
}
.app-container {
  padding-bottom: 90px;
}
.buttons {
  position: fixed;
  right: 3%;
  bottom: 2%;
}
.bottom {
  position: fixed;
  background: #fff;
  z-index: 9;
  bottom: 0;
  width: 100%;
  height: 90px;
  border-top: 2px solid #eee;
}
.imgMini {
  .avatar {
    width: 80px !important;
    height: 80px !important;
  }
  .el-icon-plus {
    width: 80px !important;
    height: 80px !important;
    line-height: 88px !important;
  }
}

.add {
  span {
    font-size: 18px;
    font-weight: 900;
  }
  button {
    float: right;
  }
}
.sacw {
  background: #2870b5;
  color: #fff;
}
hr {
  border: 1px solid #eee;
  margin-bottom: 20px;
}
.top {
  span {
    font-size: 20px;
    font-weight: 900;
  }
  div {
    float: right;
  }
}
</style>
